package com.mlink.ai.chat.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.mlink.ai.chat.bean.ExploreCategory
import com.mlink.ai.chat.bean.ExploreSubCategory
import com.mlink.ai.chat.utils.AnalyticsEvents
import com.mlink.ai.chat.utils.AnalyticsParams
import com.mlink.ai.chat.utils.NotificationUtils
import com.mlink.ai.chat.utils.PromptUtils
import com.mlink.ai.chat.utils.logEvent
import com.tencent.mmkv.MMKV

class PromptLocalNotificationAlarmReceiver : BroadcastReceiver() {

    private var promptList: MutableList<ExploreSubCategory>? = null
    private var categoryList: List<ExploreCategory>? = null

    override fun onReceive(context: Context?, intent: Intent?) {

        if (promptList == null) {
            context?.let {
                categoryList = PromptUtils.getPresetPromptCategoryList(context)
                promptList = mutableListOf<ExploreSubCategory>().apply {
                    val maxLength = categoryList!!.maxOfOrNull { it.subCategories.size } ?: 0
                    for (i in 0 until maxLength) {
                        for (category in categoryList!!) {
                            if (i < category.subCategories.size) {
                                add(category.subCategories[i])
                            }
                        }
                    }
                }
            }
        }

        promptList?.let {
            if (it.isNotEmpty() && context != null) {
                val lastIndex = MMKV.defaultMMKV().getInt(PROMPT_LOCAL_NOTIFICATION_LAST_INDEX, -1)
                var index = lastIndex + 1
                if (index >= it.size) {
                    index = 0
                }
                val subCategory = it[index]
                var categoryEventName = ""
                categoryList?.forEach { exploreCategory ->
                    if (subCategory.parentCategoryId == exploreCategory.id) {
                        categoryEventName = exploreCategory.categoryEventName ?: ""
                    }
                }
                NotificationUtils.showPromptLocalNotification(context, subCategory, categoryEventName)
                MMKV.defaultMMKV().encode(PROMPT_LOCAL_NOTIFICATION_LAST_INDEX, index)
                AnalyticsEvents.AC_PUSH_PPT_SHOW.logEvent(
                    Bundle().apply {
                        putString(AnalyticsParams.CATEGORY, categoryEventName)
                        putString(AnalyticsParams.KEY_TITLE, subCategory.categoryEventName)
                    }
                )
            }
        }
    }

    companion object {
        private const val PROMPT_LOCAL_NOTIFICATION_LAST_INDEX = "prompt_local_notification_last_index"
    }
}